package bigo.data;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.TreeMap;
import org.apache.hadoop.io.Writable;

/**
 *
 * @author Song
 */
public class ArrayVectorCombo extends TreeMap<Integer, ArrayVector> implements Writable {

    public void addVector(ArrayVector v) {
        if (containsKey(v.getOffset())) {
            for (int i = 0; i < v.size(); i++) {
                get(v.getOffset()).getVector()[i] += v.getVector()[i];
            }
        } else {
            put(v.getOffset(), v);
        }
    }

    public void addCombo(ArrayVectorCombo combo) {
        for (Integer i : combo.keySet()) {
            addVector(combo.get(i));
        }
    }

    public ArrayVector toArrayVector() {
        int length = 0;
        for (ArrayVector v : values()) {
            length += v.length();
        }
        ArrayVector ret = new ArrayVector(length);
        for (ArrayVector v : values()) {
            System.arraycopy(v.getVector(), 0, ret.getVector(), v.getOffset(), v.length());
        }
        return ret;
    }

    public void write(DataOutput out) throws IOException {
        out.writeInt(size());
        for (Integer offset : keySet()) {
            get(offset).write(out);
        }
    }

    public void readFields(DataInput in) throws IOException {
        clear();
        int len = in.readInt();
        for (int i = 0; i < len; i++) {
            ArrayVector v = new ArrayVector();
            v.readFields(in);
            put(v.getOffset(), v);
        }
    }
}
